//
//  String+Separator.swift
//  TTCOM
//
//  Created by Toj on 12/30/22.
//

import Foundation

public extension String {
    // SP: Separator
    enum SPFormatterType {
        case none
        // 000 0000 0000
        case threeFourFour
        // 0000 0000 000
        case fourFourThree
        
        var indexs: [Int] {
            switch self {
            case .threeFourFour:
                return [3, 8, 13]
            case .fourFourThree:
                return [4, 9, 13]
            default:
                return []
            }
        }
    }
    
    func cm_numberFormat(format type: SPFormatterType, separator: String = " ") -> String {
        guard !separator.isEmpty, type != .none else {
            return self
        }
       
        let cseparator = Character(separator)
        var cardNumber = replacingOccurrences(of: separator, with: "")
        let startIndex = cardNumber.startIndex
        switch type {
        case .threeFourFour:
            // 12345678901
            if cardNumber.count <= 3 { break }
            // 123 45678901
            var index = cardNumber.index(startIndex, offsetBy: 3)
            
            cardNumber.insert(cseparator, at: index)
            
            // 123 45678901
            if cardNumber.count <= 8 { break }
            // 123 4567 8901
            index = cardNumber.index(startIndex, offsetBy: 8)
            cardNumber.insert(cseparator, at: index)
        case .fourFourThree:
            // 12345678901
            if cardNumber.count <= 4 { break }
            // 1234 5678901
            var index = cardNumber.index(startIndex, offsetBy: 4)
            cardNumber.insert(cseparator, at: index)
            
            // 1234 5678901
            if cardNumber.count <= 9 { break }
            
            // 1234 5678 901
            index = cardNumber.index(startIndex, offsetBy: 9)
            cardNumber.insert(cseparator, at: index)
        default:
            break
        }
        
        return cardNumber
    }
}
